package com.iiot.bytes;

public class HexStr {
    private static final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();
    // 或者小写： "0123456789abcdef".toCharArray();

    /**
     * 将字节数组转换为十六进制字符串（大写）
     * 例如: [0x1A, 0x2B] -> "1A2B"
     *
     * @param data 字节数组
     * @return 十六进制字符串
     */
    public static String toStr(byte[] data) {
        if (data == null) return null;
        StringBuilder sb = new StringBuilder(data.length * 2);
        for (byte b : data) {
            sb.append(HEX_CHARS[(b >> 4) & 0x0F]);
            sb.append(HEX_CHARS[b & 0x0F]);
        }
        return sb.toString();
    }

    /**
     * 将十六进制字符串转换为字节数组
     * 例如: "1A2B" -> [0x1A, 0x2B]
     * 支持大小写，自动忽略非十六进制字符（如空格、换行等）
     *
     * @param hexStr 十六进制字符串
     * @return 字节数组
     * @throws IllegalArgumentException 如果字符串包含非法字符或长度为奇数
     */
    public static byte[] toArray(String hexStr) {
        if (hexStr == null) return null;

        // 过滤掉所有非十六进制字符
        StringBuilder clean = new StringBuilder();
        for (char c : hexStr.toCharArray()) {
            if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) {
                clean.append(c);
            }
        }

        String cleanStr = clean.toString();
        if (cleanStr.length() % 2 != 0) {
            throw new IllegalArgumentException("Invalid hex string length: must be even. Got: " + hexStr);
        }

        byte[] bytes = new byte[cleanStr.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            int idx = i * 2;
            int high = Character.digit(cleanStr.charAt(idx), 16);
            int low = Character.digit(cleanStr.charAt(idx + 1), 16);
            bytes[i] = (byte) ((high << 4) | low);
        }
        return bytes;
    }
}
